const express = require('express');
const fs = require('fs-extra');
const path = require('path');

const router = express.Router();

/**
 * 识别平台类型从文件名
 */
function detectPlatform(fileName) {
  const name = fileName.toLowerCase();

  // 小程序平台
  if (name.includes('weixin') || name.includes('mp-weixin')) {
    return {
      platform: 'mp-weixin',
      platformName: '微信小程序',
      isMiniprogram: true,
      type: 'miniprogram'
    };
  }
  if (name.includes('alipay') || name.includes('mp-alipay')) {
    return {
      platform: 'mp-alipay',
      platformName: '支付宝小程序',
      isMiniprogram: true,
      type: 'miniprogram'
    };
  }
  if (name.includes('h5') || name === 'h5') {
    return {
      platform: 'h5',
      platformName: 'H5应用',
      isMiniprogram: false,
      type: 'h5'
    };
  }

  // 默认
  return {
    platform: 'unknown',
    platformName: '未知平台',
    isMiniprogram: false,
    type: 'unknown'
  };
}

/**
 * 提取索引号从文件名
 */
function extractIndex(fileName) {
  const match = fileName.match(/(\d+)\.zip$/);
  return match ? parseInt(match[1]) : null;
}

/**
 * 获取下载文件列表（增强版）
 * GET /api/download/list
 */
router.get('/list', async (req, res) => {
  try {
    const downloadsDir = path.join(__dirname, '../../downloads');

    if (!await fs.pathExists(downloadsDir)) {
      return res.json({ success: true, files: [] });
    }

    const files = await fs.readdir(downloadsDir);
    const fileList = await Promise.all(
      files
        .filter(file => file.endsWith('.zip'))
        .map(async file => {
          const filePath = path.join(downloadsDir, file);
          const stats = await fs.stat(filePath);

          // 识别平台类型
          const platformInfo = detectPlatform(file);

          // 提取索引号
          const index = extractIndex(file);

          return {
            fileName: file,
            fileSize: stats.size,
            createdAt: stats.birthtime,
            downloadUrl: `/downloads/${file}`,
            projectId: file.split('_')[0] || file.replace('.zip', ''), // 从文件名提取项目ID
            platform: platformInfo.platform,
            platformName: platformInfo.platformName,
            isMiniprogram: platformInfo.isMiniprogram,
            type: platformInfo.type,
            index: index
          };
        })
    );

    // 按创建时间倒序排列
    fileList.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));

    res.json({ success: true, files: fileList });

  } catch (error) {
    console.error('获取文件列表错误:', error);
    res.status(500).json({ error: '获取文件列表失败' });
  }
});

/**
 * 下载文件
 * GET /api/download/:fileName
 */
router.get('/:fileName', async (req, res) => {
  try {
    const { fileName } = req.params;
    
    // 安全检查：防止路径遍历攻击
    if (!fileName || fileName.includes('..') || fileName.includes('/')) {
      return res.status(400).json({ error: '无效的文件名' });
    }

    const filePath = path.join(__dirname, '../../downloads', fileName);
    
    if (!await fs.pathExists(filePath)) {
      return res.status(404).json({ error: '文件不存在' });
    }

    const stats = await fs.stat(filePath);
    
    // 设置下载响应头
    res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
    res.setHeader('Content-Type', 'application/zip');
    res.setHeader('Content-Length', stats.size);
    
    // 创建文件流并发送
    const fileStream = fs.createReadStream(filePath);
    fileStream.pipe(res);
    
    fileStream.on('error', (error) => {
      console.error('文件流错误:', error);
      if (!res.headersSent) {
        res.status(500).json({ error: '文件读取失败' });
      }
    });

  } catch (error) {
    console.error('下载错误:', error);
    res.status(500).json({ error: '下载失败' });
  }
});

/**
 * 删除下载文件
 * DELETE /api/download/:fileName
 */
router.delete('/:fileName', async (req, res) => {
  try {
    const { fileName } = req.params;
    
    // 安全检查
    if (!fileName || fileName.includes('..') || fileName.includes('/')) {
      return res.status(400).json({ error: '无效的文件名' });
    }

    const filePath = path.join(__dirname, '../../downloads', fileName);
    
    if (!await fs.pathExists(filePath)) {
      return res.status(404).json({ error: '文件不存在' });
    }

    await fs.remove(filePath);
    
    res.json({ 
      success: true, 
      message: '文件删除成功' 
    });

  } catch (error) {
    console.error('删除文件错误:', error);
    res.status(500).json({ error: '删除失败' });
  }
});

/**
 * 获取文件信息
 * GET /api/download/info/:fileName
 */
router.get('/info/:fileName', async (req, res) => {
  try {
    const { fileName } = req.params;
    
    // 安全检查
    if (!fileName || fileName.includes('..') || fileName.includes('/')) {
      return res.status(400).json({ error: '无效的文件名' });
    }

    const filePath = path.join(__dirname, '../../downloads', fileName);
    
    if (!await fs.pathExists(filePath)) {
      return res.status(404).json({ error: '文件不存在' });
    }

    const stats = await fs.stat(filePath);
    
    res.json({ 
      success: true,
      fileInfo: {
        fileName,
        fileSize: stats.size,
        createdAt: stats.birthtime,
        modifiedAt: stats.mtime,
        downloadUrl: `/downloads/${fileName}`,
        projectId: fileName.split('_')[0]
      }
    });

  } catch (error) {
    console.error('获取文件信息错误:', error);
    res.status(500).json({ error: '获取文件信息失败' });
  }
});

/**
 * 清理过期文件
 * POST /api/download/cleanup
 */
router.post('/cleanup', async (req, res) => {
  try {
    const { maxAge = 24 } = req.body; // 默认24小时
    const downloadsDir = path.join(__dirname, '../../downloads');
    
    if (!await fs.pathExists(downloadsDir)) {
      return res.json({ success: true, message: '没有文件需要清理' });
    }

    const files = await fs.readdir(downloadsDir);
    const now = new Date();
    let cleanedCount = 0;

    for (const file of files) {
      if (!file.endsWith('.zip')) continue;
      
      const filePath = path.join(downloadsDir, file);
      const stats = await fs.stat(filePath);
      
      // 计算文件年龄（小时）
      const ageInHours = (now - stats.birthtime) / (1000 * 60 * 60);
      
      if (ageInHours > maxAge) {
        await fs.remove(filePath);
        cleanedCount++;
        console.log(`🗑️  清理过期文件: ${file}`);
      }
    }

    res.json({ 
      success: true, 
      message: `清理完成，删除了 ${cleanedCount} 个过期文件`,
      cleanedCount 
    });

  } catch (error) {
    console.error('清理文件错误:', error);
    res.status(500).json({ error: '清理失败' });
  }
});

/**
 * 格式化文件大小
 */
function formatFileSize(bytes) {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

module.exports = router;
